<template>
  <div class="my-learning-page">
    <nav-bar></nav-bar>
    <div class="my-learning-content">
      <div class="page-header">
        <h1>我的学习</h1>
        <div class="learning-tabs">
          <div 
            v-for="(tab, index) in tabs" 
            :key="index"
            class="tab"
            :class="{ active: currentTab === tab.name }"
            @click="currentTab = tab.name"
          >
            {{ tab.name }}
          </div>
        </div>
      </div>
      
      <div class="learning-container">
        <div class="section">
          <div class="courses-grid">
            <template v-if="currentCourses.length">
              <div class="course-card" v-for="course in currentCourses" :key="course.title">
                <div class="course-info">
                  <div class="course-header">
                    <span class="instructor-name">{{ course.instructor }}</span>
                  </div>
                  <h3 class="course-title">{{ course.title }}</h3>
                  <div class="course-progress">
                    <div class="progress-bar">
                      <div class="progress" :style="{ width: calculateProgress(course) + '%' }"></div>
                    </div>
                    <span class="progress-text">{{ calculateProgress(course) }}%</span>
                  </div>
                  <button class="continue-btn" @click="continueLearning(course)">{{ course.buttonText || '继续' }}</button>
                </div>
                <div v-if="course.planDuration && course.dailyMinutes && course.chapters && course.chapters.length" class="study-plan-table-wrapper">
                  <h4 style="margin: 16px 0 8px; color: #6d28d2;">智能学习计划</h4>
                  <table class="study-plan-table">
                    <thead>
                      <tr>
                        <th>天数</th>
                        <th>建议学习内容</th>
                        <th>建议学习时长</th>
                        <th>完成状态</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(plan, idx) in generateDailyPlan(course)" :key="idx">
                        <td>第{{ idx + 1 }}天</td>
                        <td>{{ plan.lessonTitle }}</td>
                        <td>{{ course.dailyMinutes }}分钟</td>
                        <td>
                          <button v-if="!getDailyStatus(course, idx)" @click="markDailyComplete(course, idx)" class="mark-btn">标记已完成</button>
                          <span v-else class="done-label">已完成</span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </template>
            <div v-else class="empty-state">
              <p>暂无{{ currentTab }}的课程</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.courses-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.course-card {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  background: white;
}

.course-header {
  margin-bottom: 15px;
}

.instructor-name {
  font-size: 14px;
  color: #666;
}

.course-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  line-height: 1.4;
}

.course-progress {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.progress-bar {
  flex: 1;
  height: 4px;
  background: #f3f4f6;
  border-radius: 2px;
}

.progress {
  height: 100%;
  background: #6d28d2;
  border-radius: 2px;
}

.progress-text {
  font-size: 14px;
  color: #666;
  min-width: 45px;
}

.continue-btn {
  padding: 8px 20px;
  background: #6d28d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.continue-btn:hover {
  opacity: 0.9;
}

.learning-tabs {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.tab {
  padding: 8px 24px;
  cursor: pointer;
  color: #666;
  font-weight: 500;
  background: #f3f4f6;
  border-radius: 20px;
  transition: all 0.3s;
}

.tab.active {
  background: #6d28d2;
  color: white;
}

.section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.study-plan-table-wrapper {
  margin-top: 16px;
}
.study-plan-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 8px;
  font-size: 14px;
}
.study-plan-table th, .study-plan-table td {
  border: 1px solid #e5e7eb;
  padding: 6px 10px;
  text-align: left;
}
.study-plan-table th {
  background: #f3f4f6;
  color: #6d28d2;
}
.mark-btn {
  padding: 4px 12px;
  background: #6d28d2;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.2s;
}
.mark-btn:hover:not(:disabled) {
  background: #5b21b6;
}
.mark-btn:disabled {
  background: #a3a3a3;
  cursor: not-allowed;
}
.done-label {
  color: #a3a3a3;
  font-weight: bold;
}
</style>

<script>
import NavBar from '@/components/NavBar.vue'

export default {
  name: 'MyLearningView',
  components: {
    NavBar
  },
  data() {
    return {
      currentTab: '正在进行',
      tabs: [
        { name: '正在进行' },
        { name: '已完成' }
      ],
      courses: {
        '正在进行': [],
        '已完成': []
      }
    }
  },
  created() {
    // 从localStorage获取学习课程列表
    this.loadCoursesFromStorage();
  },
  computed: {
    currentCourses() {
      return this.courses[this.currentTab] || []
    }
  },
  methods: {
    loadCoursesFromStorage() {
      // 从localStorage获取学习课程列表
      const storedCourses = JSON.parse(localStorage.getItem('learningCourses'));
      if (storedCourses) {
        this.courses = storedCourses;
      }
    },
    continueLearning(course) {
      // 跳转到课程详情页，并传递课程ID和上次学习的章节信息
      this.$router.push({
        path: '/course',
        query: { 
          id: course.id,
          chapterIndex: course.lastChapter,
          lessonIndex: course.lastLesson
        }
      });
    },
    calculateProgress(course) {
      // 如果课程没有章节信息，返回0
      if (!course.chapters) return 0;
      
      // 计算总课程数
      let totalLessons = 0;
      let completedLessons = 0;
      
      course.chapters.forEach((chapter, chapterIndex) => {
        totalLessons += chapter.lessons.length;
        
        // 如果当前章节索引小于上次学习的章节索引，则该章节的所有课程都已完成
        if (chapterIndex < course.lastChapter) {
          completedLessons += chapter.lessons.length;
        } 
        // 如果是当前正在学习的章节，则计算已完成的课程数
        else if (chapterIndex === course.lastChapter) {
          completedLessons += course.lastLesson;
        }
      });
      
      // 计算进度百分比
      return totalLessons > 0 ? Math.round((completedLessons / totalLessons) * 100) : 0;
    },
    generateDailyPlan(course) {
      // 获取所有课时（lesson）
      const lessons = [];
      if (!course.chapters) return [];
      course.chapters.forEach((chapter) => {
        (chapter.lessons || []).forEach((lesson) => {
          lessons.push(lesson.title);
        });
      });
      const totalLessons = lessons.length;
      const days = Number(course.planDuration) || 1;
      const lessonsPerDay = Math.ceil(totalLessons / days);
      const plan = [];
      for (let i = 0; i < days; i++) {
        const startIdx = i * lessonsPerDay;
        const endIdx = Math.min(startIdx + lessonsPerDay, totalLessons);
        const todayLessons = lessons.slice(startIdx, endIdx);
        plan.push({
          lessonTitle: todayLessons.length ? todayLessons.join('，') : '复习/预习',
        });
      }
      return plan;
    },
    getDailyStatus(course, idx) {
      if (!course.dailyPlanStatus) return false;
      return !!course.dailyPlanStatus[idx];
    },
    markDailyComplete(course, idx) {
      if (!course.dailyPlanStatus) {
        course.dailyPlanStatus = Array(this.generateDailyPlan(course).length).fill(false);
      }
      course.dailyPlanStatus[idx] = true;
      this.saveDailyPlanStatus(course);
    },
    saveDailyPlanStatus(course) {
      // 更新 localStorage
      let learningCourses = JSON.parse(localStorage.getItem('learningCourses')) || {};
      let inProgressCourses = learningCourses['正在进行'] || [];
      const courseIndex = inProgressCourses.findIndex(c => c.id === course.id);
      if (courseIndex !== -1) {
        inProgressCourses[courseIndex].dailyPlanStatus = course.dailyPlanStatus;
        learningCourses['正在进行'] = inProgressCourses;
        localStorage.setItem('learningCourses', JSON.stringify(learningCourses));
      }
    }
  }
}
</script>